<?php
namespace Api\Controller;
vendor('Firebase.JWT.JWT');

class UserController extends BaseController {
    public function modifyWxUserInfo() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        if (!$_POST) {
            fail("需要post请求");
        }
        $data = get_auto_data($_REQUEST);
        //将用户的头像下载到自己的服务器上
        $img_name = time() . mt_rand(10000, 50000);
        $res = http_down($data['head_img'], 'C:/phpStudy/PHPTutorial/WWW/shuidiFuDao/Public/upload/userImgHead/' . $img_name . '.png');
        if ($res) {
            $data['head_img'] = 'Public/upload/userImgHead/' . $img_name . '.png';
        }
        $modifyData = array(
            'nick_name' => $data['nick_name'],
            'gender'    => $data['gender'],
            'head_img'  => $data['head_img'],
            'country'   => $data['country'],
            'province'  => $data['province'],
            'city'      => $data['city'],
        );
        $m_user = M('user');
        $result = $m_user->where(array(
            'uid' => $uid
        ))->save($modifyData);
        if ($result) {
            succeed(null, '修改用户信息成功');
        } else {
            fail('修改用户信息失败');
        }
    }

    /**
     * 根据openid获取用户信息
     */
    public function getUserInfoByWxOpenid() {
        $data = get_trim_data($_REQUEST);
        if (!$data['loginCode']) {
            fail_name('loginCode');
        }
        $wx_sdkversion = $data['wx_sdkversion'];
        $wx_sdkversion = $wx_sdkversion ? $wx_sdkversion : '';
        $openId = get_Openid($data['loginCode']);
        if ($openId == false) {
            fail('获取用户openid错误，请重试');
        }
        $m_user = M('user');
        $userInfo = $m_user->field('uid,openid_wx,nick_name,head_img,gender')->where(array(
            'openid_wx' => $openId
        ))->find();
        if ($userInfo === null) { //未查到  则注册
            //注册
            $create_res = false;
            $user_info_created = null;
            $time = time();
            for ($i = 0; $i < 10; $i++) {
                $user_info_created = array(
                    'uid'           => createIdStr(),
                    'openid_wx'     => $openId,
                    'wx_sdkversion' => $wx_sdkversion,
                    'login_time'    => $time,
                    'create_time'   => $time,
                    'update_time'   => $time
                );
                $create_res = $m_user->add($user_info_created);
                if ($create_res !== false) { //插入数据失败
                    break;
                }
            }
            if ($create_res === false) {
                //创建失败了
                fail('创建新用户失败，请重试');
            } else {
                unset($user_info_created['login_time']);
                unset($user_info_created['create_time']);
                unset($user_info_created['update_time']);
                $token ['uid'] = $user_info_created['uid'];
                $token ['time'] = time();
                $jwt = \Firebase\JWT\JWT::encode($token, C('COOKIE'));
                $user_info_created['token'] = $jwt;
                $user_info_created['nick_name'] = '';
                $user_info_created['head_img'] = '';
                $user_info_created['gender'] = 0;
                $user_info_created['share_imgcover'] = 'Public/images/sharebg1.png';
                succeed(get_auto_data($user_info_created), '创建新用户成功');
            }
        } else if ($userInfo === false) {
            //查询出错
            fail('获取数据失败，请重试');
        } else {
            //更新用户信息
            if ($wx_sdkversion) {
                $m_user->where(array(
                    'openid_wx' => $openId
                ))->save(array(
                    'wx_sdkversion' => $wx_sdkversion
                ));
            }
            $token ['uid'] = $userInfo['uid'];
            $token ['time'] = time();
            $jwt = \Firebase\JWT\JWT::encode($token, C('COOKIE'));
            $userInfo['token'] = $jwt;
            $userInfo['share_imgcover'] = 'Public/images/sharebg1.png';
            succeed(get_auto_data($userInfo), '获取用户信息成功');
        }
    }

    public function getUserQuestionCountandBalance() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $res = M()->query("select (SELECT count(q.qid) FROM t_question q WHERE q.uid='{$uid}')
                as questionCount,u.balance from t_user u 
               WHERE u.uid='{$uid}'");
        $res[0]['webTitle'] = '关注公众号';
        $res[0]['webUrl'] = 'https://mp.weixin.qq.com/s/cF0QqGJoCYIyQJvITDFICQ';
        $res[0]['actionTitle'] = '';
        $res[0]['actionDesc'] = '';
        $res[0]['rankRule'] = '';
        succeed($res[0]);
    }

    //添加formId
    public function addWXformId() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        if (!$_POST) {
            fail("需要post请求");
        }
        $data = get_auto_data($_REQUEST);
        $uid = $data['uid'];
        $openid = $data['openid'];
        $formid = $data['formid'];
        $expire = $data['expire'];
        if (!$uid || !$openid || !$formid || $formid == 'undefined' || !$expire) {
            fail_name('参数错误', '');
        }
        if ($formid == 'the formId is a mock one') {
            fail('the formId is a mock one');
        }
        //看看有没有这个用户
        $exist = M('user')->field('uid')->where(array(
            'uid' => $uid
        ))->count();
        if ($exist <= 0) {
            fail('未找到该用户');
        }
        $result = M('wxformid')->add(array(
            'uid'    => $uid,
            'openid' => $openid,
            'formid' => $formid,
            'expire' => $expire,
        ));
        if (!$result) {
            fail('插入失败');
        }
        succeed('插入成功');
    }

    public function getStudents() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $pageNo = $data['pageNo'];
        $pageSize = $data['pageSize'];
        if (!is_numeric($pageNo) || $pageNo < 0) {
            fail_name('pageNo');
        }
        if (!is_numeric($pageSize) || $pageSize < 0) {
            fail_name('pageSize');
        }
        $queryIndexStart = $pageNo * $pageSize;
        $student_list = M()->query("select u.uid,u.gender,u.age,u.nick_name,u.head_img,
                      u.country,u.province,u.city,u.balance,u.create_time,
                       count(q.qid) AS questionCount
                      from t_user as u LEFT JOIN t_question as q ON q.uid=u.uid
                      GROUP BY u.uid
                      order by u.create_time desc
                    limit {$queryIndexStart},{$pageSize};");
        succeed(get_auto_data($student_list));
    }

    public function addBalance() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $student_id = $data['student_id'];
        $balance = $data['balance'];
        if (!$student_id) {
            fail_name('student_id');
        }
        if (!is_float($balance) && !is_int($balance)) {
            fail("充值金额有误");
            return;
        }
        //充值，用事务
        M()->startTrans();
        $current_time = time();
        $res = M('user')->where(array(
            'uid' => $student_id
        ))->save(array(
            'balance'     => array('exp', 'balance+' . $balance),
            'update_time' => $current_time
        ));
        //记录到日志中
        $log_add_res = M('balance_add_log')->add(array(
            'uid'         => $student_id,
            'money'       => $balance,
            'create_time' => $current_time,
            'update_time' => $current_time
        ));
        if ($res && $log_add_res) {
            $res1 = M()->commit();
            succeed(null, '充值成功' . $res1);
        } else {
            M()->rollback();
            fail('充值失败');
        }
    }

    /**
     * 充值前的解锁
     */
    public function balanceUnlock() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $pwd = $data['pwd'];
        if (!$pwd) {
            fail_name('pwd');
        }
        //校验密码输入是否正确
        $user = M('admin_user')->field('uid,password,salt')->where(array(
            'uid' => $uid
        ))->find();
        if (!$user) {
            fail('未找到用户信息');
        }
        if (jiami($pwd . $user['salt']) == $user['password']) {
            succeed(null, '解锁成功');
        } else {
            fail('密码输入有误');
        }
    }

    /**
     * 更新用户排名信息
     */
    public function updateRankData() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $uid_leader = $data['uid_leader'];
        if (!$uid_leader) {
            fail_name('uid_leader');
        }
        $uid_member = $data['uid_member'];
        if (!$uid_member) {
            fail_name('uid_member');
        }
        //自己不能助力自己
        if ($uid_leader == $uid_member) {
            fail('自己不能助力自己');
        }
        //检测是否已经助力
        $count = M('ranking')->where(array(
            'uid_leader' => $uid_leader,
            'uid_member' => $uid_member,
        ))->count();
        if ($count > 0) {
            fail('您已助力了');
        } else {
            //充值，用事务
            M()->startTrans();
            $balance = 0.01;
            $current_time = time();
            //排名记录表
            $res_rank_add = M('ranking')->add(array(
                'uid_leader'  => $uid_leader,
                'uid_member'  => $uid_member,
                'create_time' => $current_time,
                'update_time' => $current_time,
            ));
            $res = M('user')->where(array(
                'uid' => $uid_leader
            ))->save(array(
                'balance'     => array('exp', 'balance+' . $balance),
                'update_time' => $current_time
            ));
            //记录到日志中
            $log_add_res = M('balance_add_log')->add(array(
                'uid'         => $uid_leader,
                'money'       => $balance,
                'type'        => 2,
                'rank_id'     => $res_rank_add,
                'create_time' => $current_time,
                'update_time' => $current_time
            ));
            if ($res_rank_add && $res && $log_add_res) {
                M()->commit();
                succeed(null, '助力成功');
            } else {
                M()->rollback();
                fail('助力失败');
            }
        }
    }

    public function getRankingList() {
        $rank_list = M()->query("select r.uid_leader,r.create_time,count(r.uid_leader) as total_count,u.nick_name,u.head_img,u.gender
                    from t_ranking r,t_user u
                    WHERE r.uid_leader=u.uid
                    GROUP BY r.uid_leader
                    ORDER BY total_count desc, r.create_time asc
                    limit 0,30");
        succeed(get_auto_data($rank_list));
    }

    public function myRankers() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $pageNo = $data['pageNo'];
        $pageSize = $data['pageSize'];
        if (!is_numeric($pageNo) || $pageNo < 0) {
            fail_name('pageNo');
        }
        if (!is_numeric($pageSize) || $pageSize < 0) {
            fail_name('pageSize');
        }
        $queryIndexStart = $pageNo * $pageSize;
        $rank_list = M()->query("select r.uid_leader,r.uid_member,r.create_time,u.nick_name,u.head_img,u.gender
                    from t_ranking r 
                    LEFT JOIN t_user u
                    ON r.uid_leader='{$uid}' AND u.uid=r.uid_member
                    ORDER BY r.create_time desc
                    limit {$queryIndexStart},{$pageSize};");
        //循环查出分类名称
        succeed(get_auto_data($rank_list, true));
    }
}